/*
 * Copyright (c) 2020 Carnegie Lee
 * All rights reserved
 */
package com.geekc.kafka.producer;

import com.geekc.kafka.constant.KafkaConst;
import com.geekc.kafka.domain.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

/**
 * 生产者 - 非Replying模式
 * @author Carnegie Lee
 */
@Component
public class SimpleProducer {

    @Autowired(required = false)
    private KafkaTemplate kafkaTemplate;

    /**
     * 无结果发送
     * @param message 消息体
     */
    public void send(Message message) {
        kafkaTemplate.send(KafkaConst.KAFKA_TARGET_TOPIC_SIMPLE, message);
    }

    /**
     * 同步发送消息（返回结果）
     * @param message 消息体
     * @return
     */
    public SendResult<String, Object> sendAndWaitForResult(Message message) {
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(KafkaConst.KAFKA_TARGET_TOPIC_SIMPLE, message);
        SendResult<String, Object> result = null;
        try {
            result = future.get();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 异步发送消息
     * @param message 消息体
     * @param callback 回调函数
     */
    public void asyncSend(Message message, ListenableFutureCallback callback) {
        kafkaTemplate.send(KafkaConst.KAFKA_TARGET_TOPIC_SIMPLE, message).addCallback(callback);
    }
}
